package com.gdpu.project.dao.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.gdpu.page.vo.QueryResult;
import com.gdpu.project.dao.CgConferenceDao;
import com.gdpu.project.vo.CgConference;
import com.gdpu.project.vo.CgProject;


public class CgConferenceDaoImpl extends HibernateDaoSupport implements CgConferenceDao {
	private static final Log log = LogFactory.getLog(CgConferenceDaoImpl.class);
	// property constants
	public static final String CONFERENCE_ID = "conferenceId";
	public static final String TEACHER_ID = "teacherId";
	public static final String CONFERENCE_NAME = "conferenceName";
	public static final String CONFERENCE_THEME = "conferenceTheme";
	public static final String KE_YAN_FEN = "keYanFen";
	public static final String COMMENT = "comment";

	protected void initDao() {
		// do nothing
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#save(com.gdpu.project.vo.CgConference)
	 */
	public void save(CgConference transientInstance) {
		log.debug("saving CgConference instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#delete(com.gdpu.project.vo.CgConference)
	 */
	public void delete(CgConference persistentInstance) {
		log.debug("deleting CgConference instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findById(java.lang.Integer)
	 */
	public CgConference findById(java.lang.Integer id) {
		log.debug("getting CgConference instance with id: " + id);
		try {
			CgConference instance = (CgConference) getHibernateTemplate().get(
					"com.gdpu.project.vo.CgConference", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findByExample(com.gdpu.project.vo.CgConference)
	 */
	public List<CgConference> findByExample(CgConference instance) {
		log.debug("finding CgConference instance by example");
		try {
			List<CgConference> results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findByProperty(java.lang.String, java.lang.Object)
	 */
	@SuppressWarnings("unchecked")
	public QueryResult<CgConference> findByProperty(String propertyName, Object value,int firstindex,int maxresult) {
		log.debug("finding CgConference instance with property: "
				+ propertyName + ", value: " + value);
		try {
			Query query1=getSessionFactory().getCurrentSession().createQuery("from CgConference as model where model."
					+ propertyName + " like :propertyName");
			Query query2=getSessionFactory().getCurrentSession().createQuery(" select count (*) from CgConference as model where model."
					+ propertyName + " like :propertyName");
			if(value!=null){
				query1.setParameter("propertyName",value);
				query2.setParameter("propertyName",value);
			}else{
				query1.setParameter("propertyName", "%%");
				query2.setParameter("propertyName", "%%");
			}
			if(firstindex!=-1&&maxresult!=-1){
				query1.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			QueryResult<CgConference> queryResult=new QueryResult<CgConference>();
			queryResult.setResultlist(query1.list());
			queryResult.setTotalrecord((Long)query2.uniqueResult());
			/*value !=null?query.setParameter(propertyName, value):query.setParameter(propertyName, "%%");*/
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<CgConference> nfindByProperty(String propertyName,String value,Date begin,Date end) {
		log.debug("finding CgConference instance with property: "
				+ propertyName + ", value: " + value);
		try {
			StringBuilder builder=new StringBuilder();
			String queryString = "from CgConference as model where model."
				+ propertyName + "= ?";
			builder.append(queryString);
			if(begin!=null){
				builder.append(" and model.conferenceDate>=? ");
			}
			if(end!=null){
				builder.append(" and model.conferenceDate<=? ");
			}
			List<Object> pramList=new ArrayList<Object>();
			if(value!=null){
				pramList.add(value);
			}
			if(begin!=null){
				pramList.add(begin);
			}
			if(end!=null){
				pramList.add(end);
			}
			
			return (List<CgConference>)getHibernateTemplate().find(builder.toString(), pramList.toArray());
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	 
	
	/**
	 * 分页查询学术会议
	 */
	public QueryResult<CgConference> nfindByProperty(String propertyName,List<String> value,Date begin,Date end,int firstindex,int maxresult) {
		log.debug("finding CgConference instance with property: "
				+ propertyName + ", value: " + value);
		try {
			QueryResult<CgConference> queryResult=new QueryResult<CgConference>();
			//String val[]=(String[])value.toArray();
			StringBuffer queryStr=new StringBuffer();
			queryStr.append("from CgConference as model where model."+ propertyName + " in (:value)");
			if(begin!=null){
				queryStr.append(" and model.conferenceDate>=:begin");
			}
			if(end!=null){
				queryStr.append(" and model.conferenceDate<:end");
			}
			Query query=getSessionFactory().getCurrentSession().createQuery(queryStr.toString());
			query.setParameterList("value", value);//绑定参数
			if(begin!=null){
				query.setParameter("begin", begin);
			}
			if(end!=null){
				query.setParameter("end", end);
			}
			if(firstindex!=-1&&maxresult!=-1){
				query.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			if(value.size()>0){
				queryResult.setResultlist(query.list());
			}
			queryStr.delete(0,queryStr.length());//清除之前的字符窜
			queryStr.append("select count(*) from CgConference as model where model."+ propertyName + " in (:value)");
			if(begin!=null){
				queryStr.append(" and model.conferenceDate>=:begin");
			}
			if(end!=null){
				queryStr.append(" and model.conferenceDate<:end");
			}
			query=getSessionFactory().getCurrentSession().createQuery(queryStr.toString());
			query.setParameterList("value", value);//绑定参数
			if(query.getQueryString().indexOf(" and model.conferenceDate>=:begin")!=-1){
				query.setParameter("begin", begin);
			}
			if(query.getQueryString().indexOf(" and model.conferenceDate<:end")!=-1){
				query.setParameter("end", end);
			}
			if(value.size()>0){
				queryResult.setTotalrecord((Long)query.uniqueResult());
			}
			
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}
	 

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findByConferenceId(java.lang.Object)
	 */
	public QueryResult<CgConference> findByConferenceId(Object conferenceId,int firstindex,int maxresult) {
		return findByProperty(CONFERENCE_ID, conferenceId,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findByTeacherId(java.lang.Object)
	 */
	public QueryResult<CgConference> findByTeacherId(Object teacherId,int firstindex,int maxresult) {
		return findByProperty(TEACHER_ID, teacherId,firstindex,maxresult);
	}
	public QueryResult<CgConference> findByTeacherId(Object teacherId) {
		return findByProperty(TEACHER_ID, teacherId,-1,-1);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findByConferenceName(java.lang.Object)
	 */
	public QueryResult<CgConference> findByConferenceName(Object conferenceName,int firstindex,int maxresult) {
		return findByProperty(CONFERENCE_NAME, conferenceName,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findByConferenceTheme(java.lang.Object)
	 */
	public QueryResult<CgConference> findByConferenceTheme(Object conferenceTheme,int firstindex,int maxresult) {
		return findByProperty(CONFERENCE_THEME, conferenceTheme,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findByKeYanFen(java.lang.Object)
	 */
	public QueryResult<CgConference> findByKeYanFen(Object keYanFen,int firstindex,int maxresult) {
		return findByProperty(KE_YAN_FEN, keYanFen,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findByComment(java.lang.Object)
	 */
	public QueryResult<CgConference> findByComment(Object comment,int firstindex,int maxresult) {
		return findByProperty(COMMENT, comment,firstindex,maxresult);
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#findAll()
	 */
	@SuppressWarnings("unchecked")
	public QueryResult<CgConference> findAll(int firstindex,int maxresult) {
		log.debug("finding all CgConference instances");
		try {
			QueryResult<CgConference> queryResult=new QueryResult<CgConference>();
			Query query=getSessionFactory().getCurrentSession().createQuery("from CgConference cgConference");
			if(firstindex!=-1&maxresult!=-1){
				query.setFirstResult(firstindex).setMaxResults(maxresult);
			}
			queryResult.setResultlist(query.list());
			query=getSessionFactory().getCurrentSession().createQuery("select count(*) from CgConference cgConference");
			queryResult.setTotalrecord((Long)query.uniqueResult());
			return queryResult;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#merge(com.gdpu.project.vo.CgConference)
	 */
	public CgConference merge(CgConference detachedInstance) {
		log.debug("merging CgConference instance");
		try {
			CgConference result = (CgConference) getHibernateTemplate().merge(
					detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#attachDirty(com.gdpu.project.vo.CgConference)
	 */
	public void attachDirty(CgConference instance) {
		log.debug("attaching dirty CgConference instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see com.gdpu.project.dao.impl.CgConferenceDao#attachClean(com.gdpu.project.vo.CgConference)
	 */
	public void attachClean(CgConference instance) {
		log.debug("attaching clean CgConference instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public static CgConferenceDao getFromApplicationContext(
			ApplicationContext ctx) {
		return (CgConferenceDao) ctx.getBean("CgConferenceDAO");
	}

	public List<CgConference> nfindByProperty(String propertyName, Object value) {
		// TODO Auto-generated method stub
		return null;
	}
	
	public int count(int teacherId) {
		String hql="from CgProject as c where c.teacherId=?";
		int count=0;
		List<CgProject> list=(List<CgProject>)getHibernateTemplate().find(hql, teacherId);
		Iterator<CgProject> cgproject=list.iterator();
		while(cgproject.hasNext())
		{
			CgProject c=cgproject.next();
			count=count+(int)c.getKeYanFen();
		}
		return count;
	}

	public int count(String teacherId) {
		String hql="from CgConference as c where c.teacherId=?";
		int count=0;
		List<CgConference> list=(List<CgConference>)getHibernateTemplate().find(hql, teacherId);
		Iterator<CgConference> it=list.iterator();
		while(it.hasNext())
		{
			CgConference c=it.next();
			if(c.getKeYanFen()==0f){
				count=count+0;
			}
			else{
				count=count+(int)c.getKeYanFen();
			}
		}
		return count;
	}

	
}